package com.yunyao.framework.service.impl;

import com.alibaba.fastjson2.util.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunyao.common.constant.enums.AuditStatusEnums;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.constant.enums.DateFormatPattern;
import com.yunyao.common.constant.enums.ReconciliationStatusEnum;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.core.UserInfoRequest;
import com.yunyao.common.dto.PoSyupplyDto;
import com.yunyao.common.dto.SpReconciliationDto;
import com.yunyao.common.dto.excel.ReconciliationExcelDto;
import com.yunyao.common.exception.BusinessException;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.StringUtils;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.mapper.BamuPoSupplyMaterialMapper;
import com.yunyao.dao.model.*;
import com.yunyao.dao.service.bamu.IBamuAuditConfirmHistoryService;
import com.yunyao.dao.service.bamu.IBamuContractWirePayService;
import com.yunyao.dao.service.bamu.IBamuPoSupplyMaterialService;
import com.yunyao.dao.service.bamu.IBamuPoSupplyService;
import com.yunyao.dao.service.bamu.IBamuPurchaseContractService;
import com.yunyao.dao.service.bamu.IBamuSpReconciliationOrderMaterialService;
import com.yunyao.dao.service.bamu.IBamuSpReconciliationOrderService;
import com.yunyao.dao.service.bamu.IBamuSpReconciliationService;
import com.yunyao.framework.audit.SpReconciliationAuditHandle;
import com.yunyao.framework.dto.posyupply.PoSyupplyMaterialDto;
import com.yunyao.framework.dto.spreconciliatioin.SpReconciliationApprovalDto;
import com.yunyao.framework.dto.spreconciliatioin.SpReconciliationConfirmDto;
import com.yunyao.framework.dto.spreconciliatioin.SpReconciliationSaveDto;
import com.yunyao.framework.dto.spreconciliatioin.SpReconciliationSubmitApprovalDto;
import com.yunyao.framework.service.SpReconciliationOrderService;
import com.yunyao.framework.service.SpReconciliationService;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationInfoVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationMaterialVO;
import com.yunyao.framework.vo.spreconciliation.SpReconciliationVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SpReconciliationServiceImpl implements SpReconciliationService {
    @Autowired
    private SpReconciliationOrderService spReconciliationOrderService;
    @Autowired
    private IBamuPurchaseContractService iBamuPurchaseContractService;
    @Autowired
    private SpReconciliationAuditHandle spReconciliationAuditHandle;
    @Autowired
    private IBamuContractWirePayService iBamuContractWirePayService;
    @Autowired
    private IBamuSpReconciliationService iBamuSpReconciliationService;
    @Autowired
    private IBamuSpReconciliationOrderService iBamuSpReconciliationOrderService;
    @Autowired
    private IBamuPoSupplyService iBamuPoSupplyService;
    @Autowired
    private IBamuPoSupplyMaterialService iBamuPoSupplyMaterialService;
    @Autowired
    private BamuPoSupplyMaterialMapper bamuPoSupplyMaterialMapper;
    @Autowired
    private IBamuSpReconciliationOrderMaterialService iBamuSpReconciliationOrderMaterialService;
    @Autowired
    private IBamuAuditConfirmHistoryService iBamuAuditConfirmHistoryService;

    @Override
    public YResult<PageResult<SpReconciliationVO>> pageList(SpReconciliationDto spReconciliationDto) {
        //构建查询条件
        LambdaQueryWrapper<BamuSpReconciliation> queryWrapper = new LambdaQueryWrapper<>();
        // 处理status列表
        if (spReconciliationDto.getStatusList() != null && !spReconciliationDto.getStatusList().isEmpty()) {
            queryWrapper.in(BamuSpReconciliation::getStatus, spReconciliationDto.getStatusList());
        }
        queryWrapper.eq(StringUtils.isNotBlank(spReconciliationDto.getContractId()), BamuSpReconciliation::getContractId, spReconciliationDto.getContractId())
                .eq(StringUtils.isNotBlank(spReconciliationDto.getProjectId()), BamuSpReconciliation::getProjectId, spReconciliationDto.getProjectId())
                .eq(StringUtils.isNotBlank(spReconciliationDto.getSupplierDeptId()), BamuSpReconciliation::getSupplierDeptId, spReconciliationDto.getSupplierDeptId())
                .eq(StringUtils.isNotBlank(spReconciliationDto.getContractMethod()), BamuSpReconciliation::getContractMethod, spReconciliationDto.getContractMethod())
                .eq(spReconciliationDto.getStatus() != null, BamuSpReconciliation::getStatus, spReconciliationDto.getStatus())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSpReconciliation::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuSpReconciliation::getSupplierDeptId, BaseContext.getSupplierList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSpReconciliation::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuSpReconciliation::getSupplierDeptId, BaseContext.getSupplierList())
                .like(StringUtils.isNotBlank(spReconciliationDto.getContractName()), BamuSpReconciliation::getContractName, spReconciliationDto.getContractName())
                .like(StringUtils.isNotBlank(spReconciliationDto.getProjectName()), BamuSpReconciliation::getProjectName, spReconciliationDto.getProjectName())
                .like(StringUtils.isNotBlank(spReconciliationDto.getSupplierDeptName()), BamuSpReconciliation::getSupplierDeptName, spReconciliationDto.getSupplierDeptName())
                .ge(StringUtils.isNotBlank(spReconciliationDto.getReconciliationStartDate()), BamuSpReconciliation::getReconciliationStartDate, ConvertUtil.getString2Date(spReconciliationDto.getReconciliationStartDate()))
                .le(StringUtils.isNotBlank(spReconciliationDto.getReconciliationEndDate()), BamuSpReconciliation::getReconciliationEndDate, ConvertUtil.getString2Date(spReconciliationDto.getReconciliationEndDate()))
                .like(StringUtils.isNotBlank(spReconciliationDto.getContractNo()), BamuSpReconciliation::getContractNo, spReconciliationDto.getContractNo())
                .eq(BamuSpReconciliation::getIsDeleted, 0)
                .orderByDesc(BamuSpReconciliation::getCreatedAt);
        // 分页查询
        IPage<BamuSpReconciliation> soSupplyPage = new Page<>(spReconciliationDto.getPageIndex(), spReconciliationDto.getPageSize());
        soSupplyPage = iBamuSpReconciliationService.page(soSupplyPage, queryWrapper);
        // 处理查询结果
        if (CollectionUtils.isEmpty(soSupplyPage.getRecords())) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
//        // 转换为VO对象列表
//        List<SpReconciliationVO> spReconciliationVOList = daoToVoList(soSupplyPage.getRecords());
        // 预先查询BamuContractWirePay对象
        List<String> contractIds = soSupplyPage.getRecords().stream()
                .map(BamuSpReconciliation::getContractId)
                .distinct()
                .collect(Collectors.toList());
        Map<String, BamuContractWirePay> contractWirePayMap = iBamuContractWirePayService.mapByContractIdList(contractIds);

        // 转换为VO对象列表
        List<SpReconciliationVO> spReconciliationVOList = daoToVoList(soSupplyPage.getRecords(), contractWirePayMap);
        // 返回分页结果
        return YResult.success(new PageResult<>(spReconciliationVOList, soSupplyPage.getCurrent(), soSupplyPage.getSize(), soSupplyPage.getPages(), soSupplyPage.getTotal()));
    }

    private List<SpReconciliationVO> daoToVoList(List<BamuSpReconciliation> records, Map<String, BamuContractWirePay> contractWirePayMap) {
        return records.stream().map(record -> daoToVo(record, contractWirePayMap)).collect(Collectors.toList());
    }

    private SpReconciliationVO daoToVo(BamuSpReconciliation bamuSpReconciliation, Map<String, BamuContractWirePay> contractWirePayMap) {
        SpReconciliationVO spReconciliationVO = new SpReconciliationVO();
        // 将BamuSpReconciliation对象的属性复制到SpReconciliationVO对象
        BeanUtils.copyProperties(bamuSpReconciliation, spReconciliationVO);
        // 获取BamuSpReconciliation对象的审核状态
        String auditStatus = bamuSpReconciliation.getAuditStatus();
        // 获取BamuSpReconciliation对象的流程实例ID
        String processInstanceId = bamuSpReconciliation.getProcessInstanceId();
        // 获取BamuSpReconciliation对象的模型方案信息ID
        String modelSchemeInfoId = bamuSpReconciliation.getModelSchemeInfoId();
        // 判断审核状态是否为"AUDIT"，并且模型方案信息ID和流程实例ID都不为空
        if (org.apache.commons.lang3.StringUtils.isNotBlank(auditStatus)
                && org.apache.commons.lang3.StringUtils.equals(auditStatus, AuditStatusEnums.AUDIT.getType().toString())
                && org.apache.commons.lang3.StringUtils.isNotBlank(modelSchemeInfoId)
                && org.apache.commons.lang3.StringUtils.isNotBlank(processInstanceId)) {
            // 设置SpReconciliationVO对象的审核按钮属性
            spReconciliationVO.setAuditButton(spReconciliationAuditHandle.userIsAuditButton(modelSchemeInfoId, processInstanceId));
        }
        //获取合同id
        String contractId = bamuSpReconciliation.getContractId();
        //根据合同id，获取历史对账单
        List<BamuSpReconciliation> list = iBamuSpReconciliationService.lambdaQuery()
                .eq(BamuSpReconciliation::getContractId, contractId)
                .eq(BamuSpReconciliation::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> idList = list.stream().map(BamuSpReconciliation::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuSpReconciliationOrderMaterial> resultList = iBamuSpReconciliationOrderMaterialService.lambdaQuery()
                    .in(BamuSpReconciliationOrderMaterial::getReconciliationId, idList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuSpReconciliationOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                spReconciliationVO.setHistoryTotalPrice(sum);
            }
        }
        BamuContractWirePay wirePay = contractWirePayMap.get(bamuSpReconciliation.getContractId());
        if (wirePay != null) {
            spReconciliationVO.setPriceType(wirePay.getPriceType());
            spReconciliationVO.setPaymentCycle(wirePay.getPaymentCycle());
        }
        // 返回SpReconciliationVO对象
        return spReconciliationVO;
    }


    @Override
    public YResult<SpReconciliationInfoVO> getSpReconliationById(Long id) {
        LambdaQueryWrapper<BamuSpReconciliation> wrapper = new LambdaQueryWrapper<BamuSpReconciliation>()
                .eq(BamuSpReconciliation::getId, id);
        BamuSpReconciliation bamuSpReconciliation = iBamuSpReconciliationService.getOne(wrapper);
        // 处理查询结果
        if (Objects.isNull(bamuSpReconciliation)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(daoToInfoVO(bamuSpReconciliation));
    }

    @Override
    public YResult<SpReconciliationInfoVO> getInfo(SpReconciliationDto spReconciliationDto) {
        // 提取传入参数中的结算单ID
        String id = spReconciliationDto.getId();

        // 通过ID查询对应的结算单，同时确保查询到的结算单未被删除
        BamuSpReconciliation bamuspReconciliationSettlement =
                iBamuSpReconciliationService.getByIdNoDelete(id);
        // 如果查询不到对应的结算单或结算单已被删除，则返回一个表示没有数据的错误结果
        if (Objects.isNull(bamuspReconciliationSettlement)) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 如果查询成功，则将结算单信息转换为特定的值对象，并返回一个包含该信息的成功结果
        return YResult.success(daoToInfoVO(bamuspReconciliationSettlement));
    }

    @Override
    public BigDecimal getSupplySettlementSum(@NotBlank String contractId) {
        /*List<String> soSupply = spReconciliationOrderService.getSoSupply(contractId);
        if(CollectionUtils.isEmpty(soSupply)){
            return BigDecimal.ZERO;
        }*/
        return spReconciliationOrderService.getBySupplyIdHistorySum(contractId);
    }


    private SpReconciliationInfoVO daoToInfoVO(BamuSpReconciliation bamuSpReconciliation) {
        SpReconciliationInfoVO spReconciliationInfoVO = new SpReconciliationInfoVO();
        BeanUtils.copyProperties(bamuSpReconciliation, spReconciliationInfoVO);

        //获取合同id
        String contractId = bamuSpReconciliation.getContractId();
        //根据合同id，获取历史对账单
        List<BamuSpReconciliation> list = iBamuSpReconciliationService.lambdaQuery()
                .eq(BamuSpReconciliation::getContractId, contractId)
                .lt(BamuSpReconciliation::getCreatedAt,bamuSpReconciliation.getCreatedAt())
                .eq(BamuSpReconciliation::getIsDeleted, DataDeletedStatus.NO.getType()).list();
        if(CollectionUtils.isNotEmpty(list)){
            List<String> idList = list.stream().map(BamuSpReconciliation::getId).distinct().toList();
            //查询材料表，获取所有结算单的历史结算金额
            List<BamuSpReconciliationOrderMaterial> resultList = iBamuSpReconciliationOrderMaterialService.lambdaQuery()
                    .in(BamuSpReconciliationOrderMaterial::getReconciliationId, idList)
                    .list();
            if(CollectionUtils.isNotEmpty(resultList)){
                BigDecimal sum = resultList.stream().map(BamuSpReconciliationOrderMaterial::getReconciliationPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                spReconciliationInfoVO.setHistoryTotalPrice(sum);
            }
        }
        return spReconciliationInfoVO;
    }

    @Override
    public YResult<String> saveInfo(SpReconciliationSaveDto saveDto) {
        BamuSpReconciliation bamuSpReconciliation = new BamuSpReconciliation();
//        LambdaQueryWrapper<BamuPurchaseContract> wrapper = new LambdaQueryWrapper<BamuPurchaseContract>().eq(BamuPurchaseContract::getId, saveDto.getContractId())
//                .eq(BamuPurchaseContract::getIsDeleted, DataDeletedStatus.NO.getType());
//
//        // 调用服务方法查询合同信息
//        BamuPurchaseContract bamuPurchaseContract = iBamuPurchaseContractService.getOne(wrapper);
        if (saveDto.getId() == null) {
            // 自动生成19位随机数字ID
            Random random = new Random();
            // 初始化为空字符串
            StringBuilder idBuilder = new StringBuilder();
            // 生成19位数字，如果不足前面补0
            for (int i = 0; i < 19; i++) {
                // 生成一个0-9之间的随机数
                int randomDigit = random.nextInt(10);
                // 添加到StringBuilder
                idBuilder.append(randomDigit);
            }
            String randomId = idBuilder.toString();

            // 假设BamuReconciliation有一个setId的方法
            bamuSpReconciliation.setId(randomId);
            BeanUtils.copyProperties(saveDto, bamuSpReconciliation);
            bamuSpReconciliation.setCreatedAt(ConvertUtil.getString2Date(saveDto.getCreatedAt()));
            bamuSpReconciliation.setReconciliationStartDate(ConvertUtil.getString2Date(saveDto.getReconciliationStartDate()));
            bamuSpReconciliation.setReconciliationEndDate(ConvertUtil.getString2Date(saveDto.getReconciliationEndDate()));
//            iBamuSpReconciliationService.saveOrUpdate(bamuSpReconciliation);
        } else {
            BeanUtils.copyProperties(saveDto, bamuSpReconciliation);
            bamuSpReconciliation.setCreatedAt(ConvertUtil.getString2Date(saveDto.getCreatedAt()));
            bamuSpReconciliation.setReconciliationStartDate(ConvertUtil.getString2Date(saveDto.getReconciliationStartDate()));
            bamuSpReconciliation.setReconciliationEndDate(ConvertUtil.getString2Date(saveDto.getReconciliationEndDate()));
//            iBamuSpReconciliationService.saveOrUpdate(bamuSpReconciliation);
        }
//       return YResult.success(bamuReconciliation.getId());
        // 批量保存或更新对账结算订单信息
        PoSyupplyDto soSupplyDto = new PoSyupplyDto();
        soSupplyDto.setContractId(saveDto.getContractId());
//        List<PoSyupplyVo> bamuSoSupply = (List<PoSyupplyVo>) poSyupplyServiceImpl.pageList(soSupplyDto);
        LambdaQueryWrapper<BamuPoSupply> queryWrapper = new LambdaQueryWrapper<BamuPoSupply>()
                .eq(BamuPoSupply::getContractId, soSupplyDto.getContractId())
                .eq(BamuPoSupply::getIsDeleted, DataDeletedStatus.NO.getType());
        List<BamuPoSupply> bamuSoSupply = iBamuPoSupplyService.list(queryWrapper);
        BigDecimal rreconciliationtaxTotalPrice = BigDecimal.ZERO; // 初始化为0
        for (int i = 0; i < bamuSoSupply.size(); i++) {
            // 累加taxTotalPrice到统计变量中
            rreconciliationtaxTotalPrice = rreconciliationtaxTotalPrice.add(bamuSoSupply.get(i).getTaxTotalPrice());
            LambdaQueryWrapper<BamuSpReconciliationOrder> queryWrapper1 = new LambdaQueryWrapper<BamuSpReconciliationOrder>()
                    .eq(BamuSpReconciliationOrder::getSupplyId, bamuSoSupply.get(i).getId())
                    .eq(BamuSpReconciliationOrder::getReconciliationId, bamuSpReconciliation.getId());
            BamuSpReconciliationOrder bamuReconciliationOrder1 = iBamuSpReconciliationOrderService.getOne(queryWrapper1);
            if (Objects.isNull(bamuReconciliationOrder1)) {
                BamuSpReconciliationOrder bamuReconciliationOrder = new BamuSpReconciliationOrder();
                BeanUtils.copyProperties(bamuSoSupply.get(i), bamuReconciliationOrder);
                bamuReconciliationOrder.setSupplyId(bamuSoSupply.get(i).getId());
                bamuReconciliationOrder.setReconciliationId(bamuSpReconciliation.getId());
                // 自动生成19位随机数字ID
                Random random = new Random();
                // 初始化为空字符串
                StringBuilder idBuilder = new StringBuilder();
                // 生成19位数字，如果不足前面补0
                for (int x = 0; x < 19; x++) {
                    // 生成一个0-9之间的随机数
                    int randomDigit1 = random.nextInt(10);
                    // 添加到StringBuilder
                    idBuilder.append(randomDigit1);
                }
                String randomId1 = idBuilder.toString();
                bamuReconciliationOrder.setId(randomId1);
                iBamuSpReconciliationOrderService.saveOrUpdate(bamuReconciliationOrder);
            }

        }
        bamuSpReconciliation.setReconciliationPrice(rreconciliationtaxTotalPrice);
        bamuSpReconciliation.setSupplyIncludingTaxTotalPrice(rreconciliationtaxTotalPrice);
        iBamuSpReconciliationService.saveOrUpdate(bamuSpReconciliation);
        PoSyupplyMaterialDto soSupplyOrderDto = new PoSyupplyMaterialDto();
        soSupplyOrderDto.setIdList(saveDto.getPoSupplyIdList());
//        List<PoSyupplyMaterialVO> bamuSoSupplyMaterials = (List<PoSyupplyMaterialVO>) poSyupplyOrderServiceImpl.getPoSupplyMaterialListbySupplyId(soSupplyOrderDto);
        if (soSupplyOrderDto.getIdList() != null && soSupplyOrderDto.getIdList().size() > 0) {
            LambdaQueryWrapper<BamuPoSupplyMaterial> Wrapper = new LambdaQueryWrapper<BamuPoSupplyMaterial>()
                    .in(BamuPoSupplyMaterial::getSupplyId, soSupplyOrderDto.getIdList());
            List<BamuPoSupplyMaterial> bamuSoSupplyMaterials = bamuPoSupplyMaterialMapper.selectList(Wrapper);
            for (int i = 0; i < bamuSoSupplyMaterials.size(); i++) {
                BamuSpReconciliationOrderMaterial bamuReconciliationOrderMaterial = new BamuSpReconciliationOrderMaterial();
                BeanUtils.copyProperties(bamuSoSupplyMaterials.get(i), bamuReconciliationOrderMaterial);
//                bamuReconciliationOrderMaterial.setSupplyId(bamuSoSupplyMaterials.get(i).getId());
                bamuReconciliationOrderMaterial.setReconciliationId(bamuSpReconciliation.getId());
//                bamuReconciliationOrderMaterial.setReconciliationOrderId(bamuReconciliationOrder.getId());
                iBamuSpReconciliationOrderMaterialService.saveOrUpdate(bamuReconciliationOrderMaterial);
            }
        }


        return YResult.success(bamuSpReconciliation.getId());
    }

    private void checkSaveData(SpReconciliationSaveDto saveDto) {
        String contractId = saveDto.getContractId();
        if (org.apache.commons.lang3.StringUtils.isBlank(contractId)) {
            throw new BusinessException("合同参数必传");
        }
        BamuPurchaseContract bamuPurchaseContract = iBamuPurchaseContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(bamuPurchaseContract)) {
            throw new BusinessException("未查询可用合同");
        }
        String reconciliationStartDate = saveDto.getReconciliationStartDate();
        if (org.apache.commons.lang3.StringUtils.isBlank(reconciliationStartDate)) {
            throw new BusinessException("对账开始时间参数必传");
        }
        String reconciliationEndDate = saveDto.getReconciliationEndDate();
        if (org.apache.commons.lang3.StringUtils.isBlank(reconciliationEndDate)) {
            throw new BusinessException("对账结束时间参数必传");
        }
        List<String> poSupplyIdList = saveDto.getPoSupplyIdList();
        if (CollectionUtils.isEmpty(poSupplyIdList)) {
            throw new BusinessException("清单参数必传");
        }
        List<String> distinctPoSupplyIdList =
                poSupplyIdList.stream().distinct().toList();
        if (distinctPoSupplyIdList.size() != poSupplyIdList.size()) {
            throw new BusinessException("清单参数重复");
        }
    }

    private void saveSaleContractInfo(String contractId,
                                      BamuSpReconciliation reconciliation) {
        BamuPurchaseContract purchaseContract = iBamuPurchaseContractService.getByIdNoDelete(contractId);
        if (Objects.isNull(purchaseContract)) {
            return;
        }
        reconciliation.setContractId(contractId);
        reconciliation.setContractNo(purchaseContract.getContractNo());
        reconciliation.setContractName(purchaseContract.getContractName());
        reconciliation.setPurchaseDeptId(purchaseContract.getPurchaseDeptId());
        reconciliation.setPurchaseDeptName(purchaseContract.getPurchaseDeptName());
        reconciliation.setPurchaseDeptName(purchaseContract.getPurchaseDeptName());
        reconciliation.setProjectId(purchaseContract.getProjectId());
        reconciliation.setProjectName(purchaseContract.getProjectName());
        reconciliation.setSupplyDeptId(purchaseContract.getSupplyDeptId());
        reconciliation.setSupplyDeptName(purchaseContract.getSupplyDeptName());
        reconciliation.setSupplierDeptId(purchaseContract.getSupplierDeptId());
        reconciliation.setSupplierDeptName(purchaseContract.getSupplierDeptName());
        reconciliation.setContractMethod(purchaseContract.getContractMethod());
        reconciliation.setProjectDeptId(purchaseContract.getProjectDeptId());
        reconciliation.setProjectDeptName(purchaseContract.getProjectDeptName());
        reconciliation.setContractRebatePoints(purchaseContract.getContractRebatePoints());
        BigDecimal contractRebatePoints = purchaseContract.getContractRebatePoints();
        BigDecimal contractTotalRealPrice = purchaseContract.getContractTotalRealPrice();
        if (Objects.nonNull(contractRebatePoints) && Objects.nonNull(contractTotalRealPrice)
                && contractRebatePoints.doubleValue() > BigDecimal.ZERO.doubleValue() && contractTotalRealPrice.doubleValue() > BigDecimal.ZERO.doubleValue()) {
            reconciliation.setContractRebatePrice(contractRebatePoints.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).multiply(contractTotalRealPrice));
        }

    }

    private void spReconciliationSettlementOrderBatch(List<String> posupplyIdList,
                                                      String reconciliationId, List<SpReconciliationMaterialVO> spReconciliationMaterialList) {
        // 检查对账ID列表是否为空，为空则直接返回
        if (CollectionUtils.isEmpty(posupplyIdList)) {
            throw new BusinessException("清单参数必传");
        }
        // 根据对账单ID列表查询已删除的对账单信息
        List<BamuPoSupply> bamuPoSupplyList =
                iBamuPoSupplyService.listByIdsDeleted(posupplyIdList);
        if (CollectionUtils.isEmpty(bamuPoSupplyList)) {
            throw new BusinessException("清单信息异常");
        }
        // 根据对账ID列表查询已删除的结算单列表
        List<BamuSpReconciliationOrder> spReconciliationOrderList =
                iBamuSpReconciliationOrderService.listByReconciliationSettlementIdDeleted(reconciliationId);
        List<String> oldPosupplyIdList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(spReconciliationOrderList)) {
            List<String> deleteIdList =
                    spReconciliationOrderList.stream().map(BamuSpReconciliationOrder::getSupplyId)
                            .filter(supplyId -> !posupplyIdList.contains(supplyId)).toList();
            if (CollectionUtils.isNotEmpty(deleteIdList)) {
                iBamuSpReconciliationOrderService.deletedByReconciliationIdList(deleteIdList);
                iBamuSpReconciliationOrderMaterialService.deletedByReconciliationIdList(deleteIdList);
            }
            oldPosupplyIdList =
                    spReconciliationOrderList.stream().map(BamuSpReconciliationOrder::getSupplyId).toList();
        }
        List<String> finalOldPodupplyIdList = oldPosupplyIdList;
        List<String> filterPosupplyIdList =
                posupplyIdList.stream().filter(x -> !finalOldPodupplyIdList.contains(x)).toList();
        if (CollectionUtils.isEmpty(filterPosupplyIdList)) {
            return;
        }
        List<BamuPoSupply> posupplyList =
                bamuPoSupplyList.stream().filter(x -> filterPosupplyIdList.contains(x.getId())).toList();
        // 批量保存对账单与结算单的关联关系
        reconciliationSettlementSaveBatch(posupplyList, reconciliationId, spReconciliationMaterialList);
    }

    private void reconciliationSettlementSaveBatch(List<BamuPoSupply> poSupplyList,
                                                   String reconciliationId, List<SpReconciliationMaterialVO> spReconciliationMaterialList) {
        // 将对账单信息转换为对账结算单信息列表
        List<BamuSpReconciliationOrder> spReconciliationOrderList =
                poSupplyList.stream().map(x -> reconciliationToSettlementOrder(x,
                        reconciliationId)).collect(Collectors.toList());
        // 批量保存对账结算单信息
        iBamuSpReconciliationOrderService.saveBatch(spReconciliationOrderList);
        // 遍历对账结算单信息列表，处理每张对账单的明细信息
        for (BamuSpReconciliationOrder bamuSpReconciliationOrder :
                spReconciliationOrderList) {
            // 获取当前对账结算单的唯一标识
            String id = bamuSpReconciliationOrder.getId();
            // 获取当前对账结算单关联的对账单ID
            String posupplyID = bamuSpReconciliationOrder.getSupplyId();
            // 根据对账单ID查询对应的对账明细信息
            List<BamuPoSupplyMaterial> poSupplyMaterialList =
                    iBamuPoSupplyMaterialService.listByReconciliationId(posupplyID);
            // 如果对账明细信息列表不为空，则进行处理
            if (CollectionUtils.isNotEmpty(poSupplyMaterialList)) {
                // 将对账明细信息转换为对账结算明细信息列表
                List<BamuSpReconciliationOrderMaterial> bamuSpReconciliationOrderMaterialList =
                        poSupplyMaterialList.stream().map(x -> reconciliationToSettlementOrderMaterial(x, reconciliationId, id)).toList();
                //遍历set supplyNum
                for (BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial : bamuSpReconciliationOrderMaterialList) {
                    for (SpReconciliationMaterialVO spReconciliationMaterialVO : spReconciliationMaterialList) {
                        if (bamuSpReconciliationOrderMaterial.getMaterialId().equals(spReconciliationMaterialVO.getMaterialId()) &&
                                bamuSpReconciliationOrderMaterial.getMaterialMark().equals(spReconciliationMaterialVO.getMaterialMark())) {
                            bamuSpReconciliationOrderMaterial.setSupplyNum(spReconciliationMaterialVO.getSupplyNum());
                        }
                    }
                }
                // 批量保存对账结算明细信息
                iBamuSpReconciliationOrderMaterialService.saveBatch(bamuSpReconciliationOrderMaterialList);
            }
        }
    }

    public void findByIdUpdateBatch(@Valid @NotNull List<SpReconciliationMaterialVO> spReconciliationMaterialList) {
        List<BamuSpReconciliationOrderMaterial> list = new ArrayList<>(spReconciliationMaterialList.size());
        spReconciliationMaterialList.forEach(e -> {
            BamuSpReconciliationOrderMaterial bamuSpReconciliationOrderMaterial = new BamuSpReconciliationOrderMaterial();
            BeanUtils.copyProperties(e, bamuSpReconciliationOrderMaterial);
            bamuSpReconciliationOrderMaterial.setIncludingTaxTotalPrice(e.getIncludingTaxUnitPrice().multiply(e.getSupplyNum()));
            list.add(bamuSpReconciliationOrderMaterial);
        });
        iBamuSpReconciliationOrderMaterialService.updateBatchById(list);
    }

    @Override
    public YResult<String> save(SpReconciliationSaveDto saveDto) {
        checkSaveData(saveDto);
        // 初始化结算实体对象
        BamuSpReconciliation spReconciliation = new BamuSpReconciliation();
        spReconciliation.setId(saveDto.getId());
        String contractId = saveDto.getContractId();
        saveSaleContractInfo(contractId, spReconciliation);
        // 解析并设置对账开始日期
        spReconciliation.setReconciliationStartDate(DateUtils.parseDate(saveDto.getReconciliationStartDate(), DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        // 解析并设置对账结束日期
        spReconciliation.setReconciliationEndDate(DateUtils.parseDate(saveDto.getReconciliationEndDate(),
                DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        spReconciliation.setStatus(0);
//        // 解析并设置结算日期
//        spReconciliation.setSettlementDate(DateUtils.parseDate(saveDto.getSettlementDate(),
//                DateFormatPattern.YEAR_MONTH_DAY.getPattern()));
        //设置历史金额
        if (saveDto.getId() == null) {
            spReconciliation.setHistoryTotalPrice(getSupplySettlementSum(saveDto.getContractId()));
        } else {
            spReconciliation.setHistoryTotalPrice(saveDto.getHistoryTotalPrice());
        }

        // 保存或更新结算信息
        iBamuSpReconciliationService.saveOrUpdate(spReconciliation);
        // 批量保存对账结算订单
        spReconciliationSettlementOrderBatch(saveDto.getPoSupplyIdList(),
                spReconciliation.getId(), saveDto.getSpReconciliationMaterialList());
        updateSupplyInfo(spReconciliation.getId(), spReconciliation.getContractId());
        //修改对账信息
        List<SpReconciliationMaterialVO> spVO = saveDto.getSpReconciliationMaterialList();
        if (CollectionUtils.isNotEmpty(spVO)) {
            findByIdUpdateBatch(saveDto.getSpReconciliationMaterialList());
        }
        // 返回成功结果，包含结算ID
        return YResult.success(spReconciliation.getId());
    }

    private void updateSupplyInfo(String id, String contractId) {
        BamuSpReconciliation reconciliation = new BamuSpReconciliation();
        reconciliation.setId(id);
        List<BamuPoSupply> poSupplyList =
                iBamuPoSupplyService.listByReconciliationSettlementIdDeleted(id, contractId);
        if (CollectionUtils.isEmpty(poSupplyList)) {
            return;
        }
        int supplyNum = poSupplyList.size();
//                spReconciliationOrderList.stream().map(BamuSpReconciliationOrder::getSupplyNum).mapToInt(Integer::intValue).sum();
        double supplyIncludingTaxTotalPrice =
                poSupplyList.stream().map(BamuPoSupply::getTaxTotalPrice).mapToDouble(BigDecimal::doubleValue).sum();
//        double reconciliationPrice =
//                poSupplyList.stream().map(BamuPoSupply::getReconciliationPrice).mapToDouble(BigDecimal::doubleValue).sum();
        reconciliation.setSupplyNum(supplyNum);
        reconciliation.setReconciliationNum(BigDecimal.valueOf(poSupplyList.size()));
        reconciliation.setSupplyIncludingTaxTotalPrice(BigDecimal.valueOf(supplyIncludingTaxTotalPrice));
//        reconciliation.setSettlementNum(spReconciliationSettlementOrderList.size());
        reconciliation.setReconciliationPrice(BigDecimal.valueOf(supplyIncludingTaxTotalPrice));
        iBamuSpReconciliationService.updateById(reconciliation);
    }

    /**
     * 批量保存对账结算信息
     * 该方法主要用于将对账单与结算单关联，并保存相关联的明细信息
     *
     * @param poSupplyIdList     对账单ID列表
     * @param spreconciliationId 结算单ID
     */
    private void reconciliationSaveBatch(List<String> poSupplyIdList,
                                         String spreconciliationId) {
        // 根据对账单ID列表查询已删除的对账单信息
        List<BamuPoSupply> bamuSpReconciliationList =
                iBamuPoSupplyService.listByIdsDeleted(poSupplyIdList);
        // 如果查询到的对账单列表为空，则直接返回
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(bamuSpReconciliationList)) {
            return;
        }
        // 将对账单信息转换为对账结算订单信息，并收集为列表
        List<BamuSpReconciliationOrder> bamuReconciliationOrderList =
                bamuSpReconciliationList.stream().map(x -> reconciliationToSettlementOrder(x,
                        spreconciliationId)).collect(Collectors.toList());
        // 批量保存对账结算订单信息
        iBamuSpReconciliationOrderService.saveBatch(bamuReconciliationOrderList);
        // 遍历保存后的对账结算订单信息
        for (BamuSpReconciliationOrder bamuReconciliationOrder :
                bamuReconciliationOrderList) {
            // 获取当前对账结算订单的ID
            String id = bamuReconciliationOrder.getId();
            // 获取当前对账结算订单关联的对账单ID
            String supplyId = bamuReconciliationOrder.getSupplyId();
            // 根据对账单ID查询对账订单材料信息
            List<BamuPoSupplyMaterial> reconciliationOrderMaterialList =
                    iBamuPoSupplyMaterialService.listBySupplyId(supplyId);
            // 如果对账订单材料信息列表不为空
            if (CollectionUtils.isNotEmpty(reconciliationOrderMaterialList)) {
                // 将对账订单材料信息转换为对账结算订单材料信息，并收集为列表
                List<BamuSpReconciliationOrderMaterial> bamuSpReconciliationMaterialList =
                        reconciliationOrderMaterialList.stream().map(x -> reconciliationToSettlementOrderMaterial(x, spreconciliationId, id)).toList();
                // 批量保存对账结算订单材料信息
                iBamuSpReconciliationOrderMaterialService.saveBatch(bamuSpReconciliationMaterialList);
            }
        }

    }


    /**
     * 将对账单物料信息转换为结算单物料信息
     *
     * @param bamuPoSupplyMaterial 对账单物料信息，用于填充结算单物料信息的初始数据
     *                             //     * @param spreconciliationId 结算单ID，用于标识特定的结算单
     *                             //     * @param spreconciliationOrderId 结算单订单ID，用于在结算单中标识特定的订单
     *                             //     * @return 返回转换后的结算单物料信息对象
     */
    private BamuSpReconciliationOrderMaterial reconciliationToSettlementOrderMaterial(BamuPoSupplyMaterial bamuPoSupplyMaterial,
                                                                                      String reconciliationId,
                                                                                      String reconciliationOrderId) {
        // 初始化一个新的结算单材料对象
        BamuSpReconciliationOrderMaterial spReconciliationOrderMaterial =
                new BamuSpReconciliationOrderMaterial();
        LambdaQueryWrapper<BamuSpReconciliationOrder> queryWrapper = new LambdaQueryWrapper<BamuSpReconciliationOrder>()
                .eq(BamuSpReconciliationOrder::getReconciliationId, reconciliationId);
        BamuSpReconciliationOrder spReconciliationOrder = iBamuSpReconciliationOrderService.getOne(queryWrapper);
        // 复制对账单材料对象的属性到结算单材料对象
        BeanUtils.copyProperties(bamuPoSupplyMaterial,
                spReconciliationOrderMaterial);
        BigDecimal decimal = spReconciliationOrderMaterial.getTax().add(new BigDecimal("1"));
        BigDecimal excludingTaxUnitPrice = spReconciliationOrderMaterial.getIncludingTaxUnitPrice().divide(decimal, BigDecimal.ROUND_CEILING);
        spReconciliationOrderMaterial.setExcludingTaxUnitPrice(excludingTaxUnitPrice);
        spReconciliationOrderMaterial.setReconciliationNum(bamuPoSupplyMaterial.getComfirmSupplyNum());
        spReconciliationOrderMaterial.setReconciliationPrice(bamuPoSupplyMaterial.getIncludingTaxTotalPrice());
        // 设置结算单ID
        spReconciliationOrderMaterial.setReconciliationId(reconciliationId);
        // 设置结算单项ID
        spReconciliationOrderMaterial.setReconciliationOrderId(reconciliationOrderId);
        spReconciliationOrderMaterial.setReconciliationOrderSn(spReconciliationOrder.getOrderSn());
        // 为新生成的结算单材料对象设置一个空的ID，表示它是一个新对象
        spReconciliationOrderMaterial.setId(null);
        // 返回新的结算单材料对象
        return spReconciliationOrderMaterial;
    }


    private BamuSpReconciliationOrder reconciliationToSettlementOrder(BamuPoSupply bamuPoSupply, String reconciliationId) {
        // 初始化一个新的结算单对象
        BamuSpReconciliationOrder spReconciliationOrder =
                new BamuSpReconciliationOrder();
        // 复制对账结果的属性到结算单对象
        BeanUtils.copyProperties(bamuPoSupply, spReconciliationOrder);
        // 设置结算单的唯一ID
        spReconciliationOrder.setReconciliationId(reconciliationId);
        // 保留原对账单的ID
        spReconciliationOrder.setSupplyId(bamuPoSupply.getId());
        // 将结算单对象的ID设置为null，标记这是一个新的记录
        spReconciliationOrder.setId(null);
        // 返回转换后的结算单对象
        return spReconciliationOrder;
    }

    @Override
    public YResult<Boolean> deleteInfo(SpReconciliationSaveDto saveDto) {
        // 根据ID查询要删除的BamuPoSupply对象
        BamuSpReconciliation bamuSpReconciliation = iBamuSpReconciliationService.getById(Long.valueOf(saveDto.getId()));

        // 如果对象不存在，返回错误信息
        if (bamuSpReconciliation == null) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 调用Service层删除方法
        boolean removed = iBamuSpReconciliationService.removeById(Long.valueOf(saveDto.getId()));

        // 返回删除结果
        if (removed) {
            return YResult.success(true);
        } else {
            return YResult.error(ResultMsgEnum.ERROR);
        }
    }


    @Override
    public YResult<String> submitApproval(SpReconciliationSubmitApprovalDto approvalDto) {
        try {
            // 调用审批处理方法来提交审批
            spReconciliationAuditHandle.submit(approvalDto.getId());
            // 如果审批提交成功，返回一个包含审批ID的成功结果
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 如果审批提交过程中发生异常，记录错误日志
            log.error("提交审批异常", e);
            // 如果审批提交过程中发生异常，返回错误结果，包含异常信息
            return YResult.error(ResultMsgEnum.SUBMIT_APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> approval(SpReconciliationApprovalDto approvalDto) {
        // 尝试调用审批处理方法执行采购合同审批操作
        try {
            spReconciliationAuditHandle.approval(approvalDto);
            // 审批成功，返回成功结果对象，携带审批ID
            return YResult.success(approvalDto.getId());
        } catch (Exception e) {
            // 审批过程中发生异常，返回错误结果，携带异常信息
            return YResult.error(ResultMsgEnum.APPROVAL_ERROR);
        }
    }

    @Override
    public YResult<String> confirm(SpReconciliationConfirmDto spReconciliationConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = spReconciliationConfirmDto.getId();
        String reconciliationconfirmDate =
                spReconciliationConfirmDto.getReconciliationConfirmDate();
        String reconciliationConfirmPerson =
                spReconciliationConfirmDto.getReconciliationConfirmPerson();
        String reconciliationFile =
                spReconciliationConfirmDto.getReconciliationFile();
        String reconciliationConfirmMark =
                spReconciliationConfirmDto.getReconciliationConfirmMark();
        if (!ConvertUtil.isValidNotEmptyJson(reconciliationFile)) {
            reconciliationFile = "[]";
        }
        boolean isConfirmReconciliation = spReconciliationConfirmDto.getReconciliationConfirmStatus();
        // 根据ID获取结算信息，确保未被删除
        BamuSpReconciliation reconciliation =
                iBamuSpReconciliationService.getByIdNoDelete(id);
        if (Objects.isNull(reconciliation)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliation.getStatus();
        if (status != ReconciliationStatusEnum.CONFIRMED_BY_SUPPLIER.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error("供应商对账状态非待确认");
        }
        int reconciliationStatus = isConfirmReconciliation ?
                ReconciliationStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType() :
                ReconciliationStatusEnum.SUPPLIER_CONFIRMATION_REJECTION.getType();
        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliation.setStatus(reconciliationStatus);
        reconciliation.setReconciliationConfirmDate(ConvertUtil.getString2Date(reconciliationconfirmDate));
        reconciliation.setReconciliationConfirmPerson(reconciliationConfirmPerson);
        reconciliation.setReconciliationFile(reconciliationFile);
        reconciliation.setReconciliationConfirmMark(reconciliationConfirmMark);
        iBamuSpReconciliationService.updateById(reconciliation);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        Date date = ConvertUtil.getString2Date(reconciliationconfirmDate);
        iBamuAuditConfirmHistoryService.insertRecord(reconciliation.getId(), date
                , reconciliation.getReconciliationPrice(),
                reconciliationFile,
                reconciliationConfirmMark,
                reconciliationStatus, "1",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliation.getId());
    }

    @Override
    public YResult<String> check(SpReconciliationConfirmDto spReconciliationConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = spReconciliationConfirmDto.getId();
        String reconciliationconfirmDate =
                spReconciliationConfirmDto.getReconciliationConfirmDate();
        String reconciliationFile =
                spReconciliationConfirmDto.getReconciliationFile();
        String reconciliationConfirmMark =
                spReconciliationConfirmDto.getReconciliationConfirmMark();
        if (!ConvertUtil.isValidNotEmptyJson(reconciliationFile)) {
            reconciliationFile = "[]";
        }
        // 根据ID获取结算信息，确保未被删除
        BamuSpReconciliation reconciliation =
                iBamuSpReconciliationService.getByIdNoDelete(id);
        if (Objects.isNull(reconciliation)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliation.getStatus();
        if (status != ReconciliationStatusEnum.TO_BE_CHECKED.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error("供应商对账状态非待核对");
        }

        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliation.setStatus(ReconciliationStatusEnum.CHECKED_OUT.getType());
        reconciliation.setCheckFile(reconciliationFile);
        reconciliation.setCheckMark(reconciliationConfirmMark);
        iBamuSpReconciliationService.updateById(reconciliation);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        Date date = ConvertUtil.getString2Date(reconciliationconfirmDate);
        iBamuAuditConfirmHistoryService.insertRecord(reconciliation.getId(), date
                , reconciliation.getReconciliationPrice(),
                reconciliationFile,
                reconciliationConfirmMark,
                ReconciliationStatusEnum.CHECKED_OUT.getType(), "0",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliation.getId());
    }

    @Override
    public YResult<String> ycconfirm(SpReconciliationConfirmDto spReconciliationConfirmDto) {
        // 提取DTO中的ID和其他确认信息
        String id = spReconciliationConfirmDto.getId();
        String reconciliationConfirmDate =
                spReconciliationConfirmDto.getReconciliationConfirmDate();
        String reconciliationConfirmPerson =
                spReconciliationConfirmDto.getReconciliationConfirmPerson();
        String reconciliationFile =
                spReconciliationConfirmDto.getReconciliationFile();
        String reconciliationConfirmMark =
                spReconciliationConfirmDto.getReconciliationConfirmMark();
        if (!ConvertUtil.isValidNotEmptyJson(reconciliationFile)) {
            reconciliationFile = "[]";
        }
        // 根据ID获取结算信息，确保未被删除
        BamuSpReconciliation reconciliation =
                iBamuSpReconciliationService.getByIdNoDelete(id);
        if (Objects.isNull(reconciliation)) {
            // 若找不到结算信息，返回错误结果
            return YResult.error(ResultMsgEnum.NO_DATA);
        }

        // 检查结算状态是否为供应商已确认
        Integer status = reconciliation.getStatus();
        if (status != ReconciliationStatusEnum.CONFIRMED_BY_CLOUD_ACQUISITION.getType()) {
            // 若状态不正确，返回错误结果
            return YResult.error("供应商对账状态非待云采确认");
        }
        // 更新结算状态为云采购已确认，并保存确认凭证和标记
        reconciliation.setStatus(ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE.getType());
        reconciliation.setYcConfirmDate(ConvertUtil.getString2Date(reconciliationConfirmDate));
        reconciliation.setYcConfirmPerson(reconciliationConfirmPerson);
        reconciliation.setYcConfirmMark(reconciliationConfirmMark);
        iBamuSpReconciliationService.updateById(reconciliation);

        // 记录审核确认历史
        UserInfoRequest userInfo = BaseContext.getUserInfo();
        Date date = ConvertUtil.getString2Date(reconciliationConfirmDate);
        iBamuAuditConfirmHistoryService.insertRecord(reconciliation.getId(), date
                , reconciliation.getReconciliationPrice(),
                reconciliationFile,
                reconciliationConfirmMark,
                ReconciliationStatusEnum.CLOUD_ACQUISITION_CONFIRMATION_COMPLETE.getType(), "3",
                userInfo.getRealName());

        // 返回操作成功的结果
        return YResult.success(reconciliation.getId());
    }


    @Override
    public List<ReconciliationExcelDto> export(SpReconciliationDto spReconciliationDto) {
//构建查询条件
        LambdaQueryWrapper<BamuSpReconciliation> queryWrapper = new LambdaQueryWrapper<>();
        // 处理status列表
        if (spReconciliationDto.getStatusList() != null && !spReconciliationDto.getStatusList().isEmpty()) {
            queryWrapper.in(BamuSpReconciliation::getStatus, spReconciliationDto.getStatusList());
        }
        queryWrapper.eq(StringUtils.isNotBlank(spReconciliationDto.getContractId()), BamuSpReconciliation::getContractId, spReconciliationDto.getContractId())
                .eq(StringUtils.isNotBlank(spReconciliationDto.getProjectId()), BamuSpReconciliation::getProjectId, spReconciliationDto.getProjectId())
                .eq(StringUtils.isNotBlank(spReconciliationDto.getSupplierDeptId()), BamuSpReconciliation::getSupplierDeptId, spReconciliationDto.getSupplierDeptId())
                .eq(StringUtils.isNotBlank(spReconciliationDto.getContractMethod()), BamuSpReconciliation::getContractMethod, spReconciliationDto.getContractMethod())
                .eq(spReconciliationDto.getStatus() != null, BamuSpReconciliation::getStatus, spReconciliationDto.getStatus())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSpReconciliation::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuSpReconciliation::getSupplierDeptId, BaseContext.getSupplierList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getProjectList()), BamuSpReconciliation::getProjectId, BaseContext.getProjectList())
                .in(CollectionUtils.isNotEmpty(BaseContext.getSupplierList()), BamuSpReconciliation::getSupplierDeptId, BaseContext.getSupplierList())
                .like(StringUtils.isNotBlank(spReconciliationDto.getContractName()), BamuSpReconciliation::getContractName, spReconciliationDto.getContractName())
                .like(StringUtils.isNotBlank(spReconciliationDto.getProjectName()), BamuSpReconciliation::getProjectName, spReconciliationDto.getProjectName())
                .like(StringUtils.isNotBlank(spReconciliationDto.getSupplierDeptName()), BamuSpReconciliation::getSupplierDeptName, spReconciliationDto.getSupplierDeptName())
                .ge(StringUtils.isNotBlank(spReconciliationDto.getReconciliationStartDate()), BamuSpReconciliation::getReconciliationStartDate, ConvertUtil.getString2Date(spReconciliationDto.getReconciliationStartDate()))
                .le(StringUtils.isNotBlank(spReconciliationDto.getReconciliationEndDate()), BamuSpReconciliation::getReconciliationEndDate, ConvertUtil.getString2Date(spReconciliationDto.getReconciliationEndDate()))
                .like(StringUtils.isNotBlank(spReconciliationDto.getContractNo()), BamuSpReconciliation::getContractNo, spReconciliationDto.getContractNo())
                .eq(BamuSpReconciliation::getIsDeleted, 0)
                .orderByDesc(BamuSpReconciliation::getCreatedAt);
        List<BamuSpReconciliation> contractMaterialList = iBamuSpReconciliationService.list(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contractMaterialList)) {
            return contractMaterialList.stream().map(this::convertToExcelDto).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 将BamuContractMaterial转化成ContractMaterialExportDto
     */
    private ReconciliationExcelDto convertToExcelDto(BamuSpReconciliation bamuSpReconciliation) {
        ReconciliationExcelDto dto = new ReconciliationExcelDto();
        BeanUtils.copyProperties(bamuSpReconciliation, dto);
        dto.setId(bamuSpReconciliation.getId());
        return dto;
    }
}
